package com.ghck.server.controller.shop;

import io.swagger.annotations.ApiOperation;

import java.io.BufferedReader;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.ghck.server.GhckAplication;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.exception.GhckException;
import com.ghck.server.model.EaseUser;
import com.ghck.server.model.Maker;
import com.ghck.server.model.Pay;
import com.ghck.server.model.Users;
import com.ghck.server.model.response.Result;
import com.ghck.server.model.response.ResultList;
import com.ghck.server.model.response.ResultObject;
import com.ghck.server.model.response.UserRes;
import com.ghck.server.security.AjkUserDetails;
import com.ghck.server.service.EasemobMessageService;
import com.ghck.server.service.MakerService;
import com.ghck.server.service.PayService;
import com.ghck.server.service.UsersService;
import com.ghck.server.service.aggregation.SellerAggregationService;
import com.ghck.server.utils.AjkUtil;
import com.ghck.server.utils.FileStoreUtil;
import com.ghck.shop.constant.GoodStatus;
import com.ghck.shop.model.Category;
import com.ghck.shop.model.GoodCollect;
import com.ghck.shop.model.GoodHotSearch;
import com.ghck.shop.model.GoodsImage;
import com.ghck.shop.model.GoodsSpecification;
import com.ghck.shop.model.ImputedPrice;
import com.ghck.shop.model.OrderDetail;
import com.ghck.shop.model.Seller;
import com.ghck.shop.model.UserAddress;
import com.ghck.shop.model.UserArea;
import com.ghck.shop.model.request.GoodAddReq;
import com.ghck.shop.model.request.GoodsReq;
import com.ghck.shop.model.request.OrderInfoReq;
import com.ghck.shop.model.request.ShoppingCartReq;
import com.ghck.shop.model.response.CategoryRes;
import com.ghck.shop.model.response.GoodCollectRes;
import com.ghck.shop.model.response.GoodsRes;
import com.ghck.shop.model.response.MarketingActivityRes;
import com.ghck.shop.model.response.OrderInfoRes;
import com.ghck.shop.model.response.ShoppingCartRes;
import com.ghck.shop.service.GoodsService;
import com.ghck.shop.service.OrderService;
import com.ghck.shop.service.SellerService;
import com.ghck.shop.service.ShoppingCartService;
import com.ghck.shop.service.UserAddressService;
import com.pingplusplus.model.Charge;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.Webhooks;

@RestController
@RequestMapping("/shop")
public class ShopController {
	private final static Logger logger = LoggerFactory.getLogger(ShopController.class);
	
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserAddressService userAddressService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private PayService payService;
	@Autowired
	private SellerService sellerService;
	@Autowired
	private MakerService makerService;
	@Autowired
	private EasemobMessageService easemobMessageService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	@Autowired
	private UsersService usersService;
	
	@ApiOperation(value="商家可以使用的分类")
	@RequestMapping(value = "/goods/categoryList4ShopGood")
	@PreAuthorize(GhckAplication.all)
	public ResultList<Category> categoryList4ShopGood(){
		ResultList<Category> result = new ResultList<Category>();
		List<Category> list = goodsService.categoryList4ShopGood();
		result.setItemList(list);
		return result;
	}
	
	
	
	@ApiOperation(value="商品热搜索关键字列表")
	@RequestMapping(value = "/goods/hotSearch")
	@PreAuthorize(GhckAplication.all)
	public ResultList<GoodHotSearch> goodHotSearch(){
		ResultList<GoodHotSearch> result = new ResultList<GoodHotSearch>();
		List<GoodHotSearch> list = goodsService.allGoodHotSearchs();
		result.setItemList(list);
		return result;
	}
	
	/**
	 * 首页
	 * @param goodReq
	 * @return
	 */
	@RequestMapping(value="/home/goods/list")
	public ResultList<CategoryRes> homeList(GoodsReq goodReq){
		List<CategoryRes> list = goodsService.getHomeList(goodReq);
		return new ResultList<CategoryRes>(list);
	}
	/**
	 * 首页Banner列表
	 * @param goodReq
	 * @return
	 */
	@RequestMapping(value="/home/banner/list")
	public ResultList<CategoryRes> homeBanner(GoodsReq goodReq){
		List<CategoryRes> list = goodsService.getBannerList(goodReq);
		return new ResultList<CategoryRes>(list);
	}
	
	/**
	 * 商品分类列表
	 * @param goodReq
	 * @return
	 */
	@RequestMapping(value="/category/list")
	public ResultList<Category> categroyList(GoodsReq goodReq){
		List<Category> list = goodsService.categoryList();
		return new ResultList<Category>(list);
	}
	
	/**
	 * 商品详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/goods/detail/{id}")
	public ResultObject<GoodsRes> goodsDetail(Principal principal,@PathVariable("id") Integer id){
		GoodsReq gr = new GoodsReq();
		gr.setId(id);
		ResultObject<GoodsRes> result = new ResultObject<GoodsRes>();
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(userDetails != null){
			gr.setUserId(userDetails.getUserId());
		}
		GoodsRes goodsRes = goodsService.goodsDetail(gr);
		result.setDomain(goodsRes);
		if(goodsRes != null ){
			Seller seller  = new Seller();
			if(null != goodsRes.getSupplierId() && goodsRes.getSupplierId() != 0){
				Seller seller1 = sellerService.findSellerById(goodsRes.getSupplierId());
				if(seller !=null){
					Integer userId = seller1.getUserId();
					Users users = usersService.findUsersById(userId);
					if(null != users){
						seller.setName(users.getName());
						seller.setAvatar(users.getAvatar());
						seller.setUserId(userId);
					}
				}
			}else{
				if(userDetails != null){
					UserRes userRes = usersService.findUsersById(userDetails.getUserId());
					if(userRes.getRegionId() != null){
						Maker maker = makerService.findMakerByDistrictIdAndPass(userRes.getRegionId());
						if(null != maker){
							Users users = usersService.findUsersById(maker.getUserId());
							if(null != users){
								seller.setName(users.getName());
								seller.setAvatar(users.getAvatar());
								seller.setUserId(users.getId());
							}
						}
					}
				}
			}
			goodsRes.setSeller(seller);
		}
		return result;
	}
	
	
	
	/**
	 * 商品列表
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/goods/list")
	public ResultList<GoodsRes> goodsList(GoodsReq goodsReq){
		if(goodsReq.getLimit() == null || goodsReq.getLimit() <= 0){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "limit 不能为空");
		}
		List<GoodsRes> goodsRes = goodsService.goodsList(goodsReq);
		
		return new ResultList<GoodsRes>(goodsRes);
	}
	
	/**
	 * 新增收货地址
	 * @param principal
	 * @param userAddress
	 * @return
	 */
	@RequestMapping(value="/address/add")
	public ResultObject<UserAddress> addAddress(Principal principal,@RequestBody UserAddress userAddress){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		userAddress.setUserId(userDetails.getUserId());
		
		return new ResultObject<UserAddress>(userAddressService.addUserAddress(userAddress));
	}
	/**
	 * 获取地址
	 * @param principal
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/address/detail/{id}")
	public ResultObject<UserAddress> addressDetail(Principal principal,@PathVariable("id")Integer id){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		return new ResultObject<UserAddress>(userAddressService.getUserAddressById(id));
	}
	
	/**
	 * 修改收货地址
	 * @param principal
	 * @param userAddress
	 * @return
	 */
	@RequestMapping(value="/address/modify")
	public ResultObject<UserAddress> modifyAddress(Principal principal,@RequestBody UserAddress userAddress){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		userAddress.setUserId(userDetails.getUserId());
		
		return new ResultObject<UserAddress>(userAddressService.modifyUserAddress(userAddress));
	}
	
	/**
	 * 商品详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/address/default")
	public ResultObject<UserAddress> addAddress(Principal principal){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		UserAddress userAddress = userAddressService.getUserAddressByDefault(userDetails.getUserId());
		return new ResultObject<UserAddress>(userAddress);
	}
	
	/**
	 * 商品详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/address/all")
	public ResultList<UserAddress> allAddress(Principal principal){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		List<UserAddress>  list = userAddressService.getUserAddressAll(userDetails.getUserId());
		return new ResultList<UserAddress>(list);
	}
	
	/**
	 * 删除收货地址
	 * @param principal
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/address/delete/{id}",method=RequestMethod.PUT)
	public Result deleteAddress(Principal principal,@PathVariable("id") Integer id){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		if(null == id || id <= 0){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "ID不能为空");
		}
		userAddressService.deleteUserAddress(id);
		return new Result();
	}
	
	/**
	 * 设置默认收货地址
	 * @param principal
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/address/default/{id}",method=RequestMethod.PUT)
	public Result updateAddressToDefault(Principal principal,@PathVariable("id") Integer id){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		if(null == id || id <= 0){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "ID不能为空");
		}
		UserAddress userAddress = new UserAddress();
		userAddress.setId(id);
		userAddress.setUserId(userDetails.getUserId());
		userAddressService.updateAddressToDefault(userAddress);
		return new Result();
	}
	
	/**
	 * 创建订单
	 * @param principal
	 * @param orderInfoReq
	 * @return
	 */
	@RequestMapping(value="/order/create",method=RequestMethod.POST)
	@PreAuthorize(GhckAplication.shop_maker_user)
	public ResultObject<OrderInfoRes> createOrder(Principal principal,@RequestBody OrderInfoReq orderInfoReq){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		orderInfoReq.setUserId(userDetails.getUserId());
		ResultObject<OrderInfoRes> resultObject = new ResultObject<OrderInfoRes>();
		if(orderInfoReq.getUserAddressId() == null || orderInfoReq.getUserAddressId() <= 0){
			throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "收货地址不能为空");
		}
		if(orderInfoReq.getUserId() == null || orderInfoReq.getUserId() <= 0){
			throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户ID不能为空");
		}
		if(orderInfoReq.getOrderDetails() == null || orderInfoReq.getOrderDetails().isEmpty()){
			throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品ID不能为空");
		}
		Integer supplierId = 0;
		int index = 0;
		for(OrderDetail od : orderInfoReq.getOrderDetails()){
			GoodsRes goods = goodsService.goodsDetailById(od.getGoodsId());
			if(index == 0){
				supplierId = goods.getSupplierId();
			}else {
				if(supplierId.intValue() != goods.getSupplierId()){
					throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "一个订单的商品是能属于一个商家");
				}
			}
			index ++;
		}
		
		if(supplierId == 0){
			//系统订单
			orderInfoReq.setOrderType("0");
			UserArea ua = goodsService.findUserAreaByUserId(userDetails.getUserId());
			Maker maker = makerService.findMakerByDistrictIdAndPass(ua.getAreaId());
			if(maker == null){
				orderInfoReq.setSupplierUserId(0);
			}else {
				orderInfoReq.setSupplierUserId(maker.getUserId());
			}
		}else if(supplierId.intValue() > 0){
			//商家订单
			orderInfoReq.setOrderType("1");
			Seller seller = sellerService.findSellerById(supplierId);
			if(seller == null ){
				throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商家不存在");
			}
			orderInfoReq.setSupplierUserId(seller.getUserId());
		}
		resultObject.setDomain(orderService.createOrder(orderInfoReq));
		return resultObject;
	}
	
	/**
	 * 计算价格
	 * @param principal
	 * @param orderInfoReq
	 * @return
	 */
	@RequestMapping(value="/order/postage_calculate",method=RequestMethod.POST)
	public ResultObject<ImputedPrice> postageCalculate(Principal principal,@RequestBody OrderInfoReq orderInfoReq){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		orderInfoReq.setUserId(userDetails.getUserId());
		ResultObject<ImputedPrice> resultObject = new ResultObject<ImputedPrice>();
		resultObject.setDomain(orderService.calculatePostage(orderInfoReq));
		return resultObject;
	}
	
	/**
	 * 普通用户订单列表
	 * @param principal
	 * @param orderInfoReq
	 * @return
	 */
	@RequestMapping(value="/order/my/list",method=RequestMethod.GET)
	@PreAuthorize(GhckAplication.admin_customer_service_shop_maker_user)
	public ResultList<OrderInfoRes> orderMyList(Principal principal,OrderInfoReq orderInfoReq){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		orderInfoReq.setUserId(userDetails.getUserId());
		ResultList<OrderInfoRes> resultList = new ResultList<OrderInfoRes>();
		resultList.setItemList(orderService.userOrderList(orderInfoReq));
		return resultList;
	}
	/**
	 * 创客订单列表
	 * @param principal
	 * @param orderInfoReq
	 * @return
	 */
	@RequestMapping(value="/order/maker/list",method=RequestMethod.GET)
	@PreAuthorize(GhckAplication.shop_maker)
	public ResultList<OrderInfoRes> orderMakerList(Principal principal,OrderInfoReq orderInfoReq){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		if(orderInfoReq.getStart() == null ||orderInfoReq.getLimit() == null){
			orderInfoReq.setStart(0);
			orderInfoReq.setLimit(20);
		}
		orderInfoReq.setUserId(userDetails.getUserId());
		ResultList<OrderInfoRes> resultList = new ResultList<OrderInfoRes>();
		List<OrderInfoRes> orderInfoRes = orderService.makerOrderList(orderInfoReq);
		if(!CollectionUtils.isEmpty(orderInfoRes)){
			for(OrderInfoRes orderInfo : orderInfoRes){
				logger.info("orderInfo.getUserId() : {}",orderInfo.getUserId());
				UserRes userRes = usersService.findUsersById(orderInfo.getUserId());
				orderInfo.setUserName(userRes.getName());
				orderInfo.setUserAvatar(userRes.getAvatar());
			}
		}
		resultList.setItemList(orderInfoRes);
		return resultList;
	}
	/**
	 * 商家订单列表
	 * @param principal
	 * @param orderInfoReq
	 * @return
	 */
	@RequestMapping(value="/order/seller/list",method=RequestMethod.GET)
	@PreAuthorize(GhckAplication.shop)
	public ResultList<OrderInfoRes> orderSellerList(Principal principal,OrderInfoReq orderInfoReq){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		if(orderInfoReq.getStart() == null ||orderInfoReq.getLimit() == null){
			orderInfoReq.setStart(0);
			orderInfoReq.setLimit(20);
		}
		orderInfoReq.setUserId(userDetails.getUserId());
		ResultList<OrderInfoRes> resultList = new ResultList<OrderInfoRes>();
		
		List<OrderInfoRes> orderInfoRes = orderService.sellerOrderList(orderInfoReq);
		if(!CollectionUtils.isEmpty(orderInfoRes)){
			for(OrderInfoRes orderInfo : orderInfoRes){
				UserRes userRes = usersService.findUsersById(orderInfo.getUserId());
				orderInfo.setUserName(userRes.getName());
				orderInfo.setUserAvatar(userRes.getAvatar());
			}
		}
		resultList.setItemList(orderInfoRes);
		return resultList;
	}

	/**
	 * 订单详情
	 * @param principal
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/order/detail/{id}",method=RequestMethod.GET)
	@PreAuthorize(GhckAplication.admin_customer_service_shop_maker_user)
	public ResultObject<OrderInfoRes> orderDetail(Principal principal,@PathVariable("id") Integer id){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		if(null == id || id <= 0){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空"); 
		}
		ResultObject<OrderInfoRes> resultObject = new ResultObject<OrderInfoRes>();
		OrderInfoReq orderInfoReq = new OrderInfoReq();
		orderInfoReq.setUserId(userDetails.getUserId());
		orderInfoReq.setId(id);
		resultObject.setDomain(orderService.orderDetail(orderInfoReq));
		return resultObject;
	}
	/**
	 * 修改价格
	 * @param principal
	 * @return
	 */
	@RequestMapping(value="/order/change/{orderId}/{orderDetailId}",method=RequestMethod.POST)
	@PreAuthorize(GhckAplication.admin_shop_maker)
	public Result changeOrderGoodPrice(Principal principal,
			@PathVariable("orderId")Integer orderId,
			@PathVariable("orderDetailId")Integer orderDetailId,
			@RequestBody OrderInfoReq orderReq
			){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Result result = new Result();
		orderService.changeOrderGoodPrice(userDetails.getUserId(), orderId, orderDetailId, orderReq.getNewPrice());
		return result;
	}
	
	/**
	 * 订单详情
	 * @param principal
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/order/cancel/{id}",method=RequestMethod.PUT)
	public Result cancelOrder(Principal principal,@PathVariable("id") Integer id){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(null == userDetails){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		if(null == id || id <= 0){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空"); 
		}
		OrderInfoReq orderInfoReq = new OrderInfoReq();
		orderInfoReq.setUserId(userDetails.getUserId());
		orderInfoReq.setId(id);
		orderService.cancelOrder(orderInfoReq);
		return new Result();
	}
	
	/**
	 * 订单详情
	 * @param principal
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/generate/charge",method=RequestMethod.POST)
	public ResultObject<Charge> generateCharge(Principal principal,@RequestBody Pay pay,HttpServletRequest request){
		if(pay.getOrderId() == null || pay.getOrderId() <= 0){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "订单ID不能为空");
		}
		pay.setClientIp(AjkUtil.getClientIPAddress(request));
		ResultObject<Charge> resultObject = new ResultObject<Charge>();
		Charge charge = payService.generateCharge(pay);
		resultObject.setDomain(charge);
		return resultObject;
	}

	
	@RequestMapping(value="/webhooks/event",method=RequestMethod.POST)
	@ResponseBody
	public String webhookResult(HttpServletRequest request) throws IOException {
    		
		request.setCharacterEncoding("UTF8");
        BufferedReader reader = request.getReader();
        StringBuffer buffer = new StringBuffer();
        String string;
        while ((string = reader.readLine()) != null) {
            buffer.append(string);
        }
        reader.close();
        // 解析异步通知数据
        Event event = Webhooks.eventParse(buffer.toString());
        if ("charge.succeeded".equals(event.getType())) {
        	Charge charge = (Charge)Webhooks.parseEvnet(buffer.toString());
        	Map<String,String> extra = charge.getExtra();
        	String buyerAccount = null;
        	if(null != extra && !extra.isEmpty()){
        		if(charge.getChannel().equals("wx")){
        			buyerAccount = (null == extra.get("open_id") ) ? null : extra.get("open_id").toString();
        		}else if(charge.getChannel().equals("alipay")){
        			buyerAccount = (null == extra.get("buyer_account") ) ? null : extra.get("buyer_account").toString();
        		}else if(charge.getChannel().equals("alipay_wap")){
        			buyerAccount = (null == extra.get("buyer_account") ) ? null : extra.get("buyer_account").toString();
        		}
        	}else{
        		//如果回调成功,extra是空,则记录一条日志
        		logger.error("buyer_account:"+buffer.toString());
        	}
        	
        	String orderNo = charge.getOrderNo();
        	String chId = charge.getId();
        	orderService.webhookPayrSuccessCallBack(orderNo, charge.getChannel(), buyerAccount, chId);
        } else if ("refund.succeeded".equals(event.getType())) {
        	
        } else {
        	
        }
		return "OK";
	}
	
	@RequestMapping(value="/home/firstLocation",method=RequestMethod.GET)
	public ResultObject<MarketingActivityRes> firstLocation(
			@RequestParam(defaultValue = "0") Integer start,
            @RequestParam(defaultValue = "50") Integer limit){
		ResultObject<MarketingActivityRes> result  = new ResultObject<MarketingActivityRes>();
		MarketingActivityRes marketingActivityRes = goodsService.marketingActivityGoodsList(0, start, limit);
		result.setDomain(marketingActivityRes);
		return result;
	}
	@RequestMapping(value="/home/secondLocation",method=RequestMethod.GET)
	public ResultObject<MarketingActivityRes> secondLocation(
			@RequestParam(defaultValue = "0") Integer start,
            @RequestParam(defaultValue = "6") Integer limit){
		ResultObject<MarketingActivityRes> result  = new ResultObject<MarketingActivityRes>();
		limit = limit > 6 ? 6: limit;
		MarketingActivityRes marketingActivityRes = goodsService.marketingActivityGoodsList(1, start, limit);
		result.setDomain(marketingActivityRes);
		return result;
	}
	
	@RequestMapping(value="/goods/add",method = RequestMethod.POST)
	@PreAuthorize(value=GhckAplication.admin_shop)
	public ResultObject<GoodAddReq> addGoods(Principal principal,@RequestBody GoodAddReq goodAddReq){
		ResultObject<GoodAddReq> result = new ResultObject<GoodAddReq>();
		if(StringUtils.isEmpty(goodAddReq.getTitle())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品名称不能为空");
			throw exception;
		}
		if(StringUtils.isEmpty(goodAddReq.getDescription())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品描述不能为空");
			throw exception;
		}
		if(goodAddReq.getSalePrice() == null || goodAddReq.getSalePrice() < 0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"销售价格不能为空");
			throw exception;
		}
//		if(goodAddReq.getMarketPrice() == null || goodAddReq.getMarketPrice() < 0){
//			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"市场价格不能为空");
//			throw exception;
//		}
//		if(CollectionUtils.isEmpty(goodAddReq.getCategoryList())){
//			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品分类不能为空");
//			throw exception;
//		}
		Integer isOnsale = goodAddReq.getIsOnsale();
		if(isOnsale != null){
			if(isOnsale != GoodStatus.init && isOnsale != GoodStatus.in_review){
				GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"初始化商品状态只能是放入仓库或者提交审核");
				throw exception;
			}
		}else {
			goodAddReq.setIsOnsale(GoodStatus.init);
		}
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		Seller seller = sellerService.findSellerByUsrId(user.getUserId());
		if(seller != null){
			goodAddReq.setSupplierId(seller.getId());
		}
		result.setDomain(goodsService.addGood(goodAddReq));
		return result;
	}
	
	/**
	 * 修改商品信息
	 * @param principal
	 * @param goodAddReq
	 * @return
	 */
	@RequestMapping(value="/goods/update",method = RequestMethod.POST)
	@PreAuthorize(value=GhckAplication.admin_shop)
	public ResultObject<GoodAddReq> updateGoods(Principal principal,@RequestBody GoodAddReq goodAddReq){
		ResultObject<GoodAddReq> result = new ResultObject<GoodAddReq>();
		goodsService.updateGood(goodAddReq);
		return result;
	}
	
	
	@RequestMapping(value="/goods/add/images",method = RequestMethod.POST,consumes = "multipart/form-data")
	@PreAuthorize(value=GhckAplication.admin_shop)
	public Result addGoodsImages(Principal principal,GoodAddReq goodAddReq,@RequestParam(value="files")MultipartFile[] files){
		Result result = new Result();
		if(goodAddReq.getId() == null || goodAddReq.getId() <= 0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品ID不能为空");
			throw exception;
		}
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		List<GoodsImage> goodsImageList = new ArrayList<GoodsImage>();
		GoodsImage goodsImage = null;
		for(MultipartFile file:files){
			goodsImage = new GoodsImage();
			String fileDbName = FileStoreUtil.storeFile(file, "shop/goods/");
			logger.info("fileName:{}", fileDbName);
			goodsImage.setImageLarge(fileDbName);
			goodsImage.setImageSmall(fileDbName);
			goodsImage.setStatus(1);
			goodsImage.setSortOrder(0);
			goodsImageList.add(goodsImage);
		}
		goodAddReq.setThumbnailImage(goodsImageList.get(0).getImageSmall());
		goodAddReq.setGoodsImageList(goodsImageList);
		goodsService.updateGood(goodAddReq);
		return result;
	}
	
	/**
	 * 删除商品规格
	 * @param principal
	 * @param specificationId
	 * @return
	 */
	@RequestMapping(value="/goods/deleteGoodsSpecification/{specificationId}",method=RequestMethod.DELETE)
	@PreAuthorize(value=GhckAplication.admin_shop)
	public Result deleteGoodsSpecification(Principal principal,@PathVariable("specificationId")Integer specificationId){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		logger.info("用户:{},删除商品规格:{}", user.getUserId(),specificationId);
		Result result = new Result();
		goodsService.deleteGoodsSpecification(specificationId);
		return result;
	}
	/**
	 * 添加商品规格
	 * @param principal
	 * @param specificationId
	 * @return
	 */
	@RequestMapping(value="/goods/addGoodsSpecification/{goodId}",method=RequestMethod.POST)
	@PreAuthorize(value=GhckAplication.admin_shop)
	public Result addGoodsSpecification(Principal principal,@PathVariable("goodId")Integer goodId,@RequestBody GoodsSpecification goodsSpecification){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		logger.info("用户:{},添加商品规格:{}", user.getUserId(),JSONObject.toJSONString(goodsSpecification));
		if(goodsSpecification.getSalePrice()==null || goodsSpecification.getSalePrice() < 0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"规格售价不能为空");
			throw exception;
		}
		if(goodsSpecification.getAmount()==null || goodsSpecification.getAmount() <0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"规格库存不能为空");
			throw exception;
		}
		if(StringUtils.isEmpty(goodsSpecification.getName())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"规格名称不能为空");
			throw exception;
		}
		if(goodsSpecification.getMarketPrice()==null || goodsSpecification.getMarketPrice() <0){
			goodsSpecification.setMarketPrice(0);
		}
		if(goodsSpecification.getCostPrice()==null || goodsSpecification.getCostPrice() <0){
			goodsSpecification.setCostPrice(0);
		}
		goodsSpecification.setGoodId(goodId);
		Result result = new Result();
		goodsService.addGoodsSpecification(goodsSpecification);
		return result;
	}
	/**
	 * 修改商品规格
	 * @param principal
	 * @param specificationId
	 * @return
	 */
	@RequestMapping(value="/goods/updateGoodsSpecification",method=RequestMethod.POST)
	@PreAuthorize(value=GhckAplication.admin_shop)
	public Result updateGoodsSpecification(Principal principal,@RequestBody GoodsSpecification goodsSpecification){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		logger.info("用户:{},修改商品规格:{}", user.getUserId(),JSONObject.toJSONString(goodsSpecification));
		if(goodsSpecification.getSalePrice()==null || goodsSpecification.getSalePrice() <0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"规格售价不能为空");
			throw exception;
		}
		if(goodsSpecification.getAmount()==null || goodsSpecification.getAmount() <0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"规格库存不能为空");
			throw exception;
		}
		if(StringUtils.isEmpty(goodsSpecification.getName())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"规格名称不能为空");
			throw exception;
		}
		if(goodsSpecification.getMarketPrice()==null || goodsSpecification.getMarketPrice() <0){
			goodsSpecification.setMarketPrice(0);
		}
		if(goodsSpecification.getCostPrice()==null || goodsSpecification.getCostPrice() <0){
			goodsSpecification.setCostPrice(0);
		}
		Result result = new Result();
		goodsService.updateGoodsSpecification(goodsSpecification);
		return result;
	}
	/**
	 * 删除商品图片
	 * @param principal
	 * @param imageId
	 * @return
	 */
	@RequestMapping(value="/goods/deleteGoodImage/{imageId}",method=RequestMethod.DELETE)
	@PreAuthorize(value=GhckAplication.admin_shop)
	public Result deleteGoodImage(Principal principal,@PathVariable("imageId")Integer imageId){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		logger.info("用户:{},添加商品图片:{}", user.getUserId(),imageId);
		Result result = new Result();
		goodsService.deleteGoodImage(imageId);
		return result;
	}
	
	/**
	 * 添加商品图片
	 * @param principal
	 * @param imageId
	 * @return
	 */
	@RequestMapping(value="/goods/addGoodImage/{goodId}",method=RequestMethod.POST,consumes = "multipart/form-data")
	@PreAuthorize(value=GhckAplication.admin_shop)
	public Result addGoodImage(Principal principal,@PathVariable("goodId")Integer goodId,@RequestParam(value="files")MultipartFile[] files){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		logger.info("用户:{},添加商品图片:{}", user.getUserId(),goodId);
		if(files == null || files.length==0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品图片不能为空");
			throw exception;
		}
		Result result = new Result();
		List<GoodsImage> goodsImageList = new ArrayList<GoodsImage>();
		GoodsImage goodsImage = null;
		for(MultipartFile file:files){
			goodsImage = new GoodsImage();
			String fileDbName = FileStoreUtil.storeFile(file, "shop/goods/");
			logger.info("fileName:{}", fileDbName);
			goodsImage.setImageLarge(fileDbName);
			goodsImage.setImageSmall(fileDbName);
			goodsImage.setStatus(1);
			goodsImage.setGoodsId(goodId);
			goodsImage.setSortOrder(0);
			goodsImageList.add(goodsImage);
		}
		logger.info("{}", JSONObject.toJSONString(goodsImageList));
		goodsService.addGoodImage(goodsImageList);
		return result;
	}
	/**
	 * 卖家获取我的商品列表
	 * @param principal
	 * @param isOnsale
	 * @param start
	 * @param limit
	 * @return
	 */
	@RequestMapping(value="/goods/sellerGoods",method=RequestMethod.GET)
	@PreAuthorize(value=GhckAplication.admin_shop)
	public ResultList<GoodsRes> sellerGoods(Principal principal,
			@RequestParam(required=false,value="isOnsale")Integer isOnsale,
			@RequestParam(defaultValue = "0") Integer start,
            @RequestParam(defaultValue = "20") Integer limit
			){
		ResultList<GoodsRes> result = new ResultList<GoodsRes>();
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		Seller seller = sellerService.findSellerByUsrId(user.getUserId());
		if(seller != null){
			List<GoodsRes> list = goodsService.findGoodsBySupplierId(seller.getId(), isOnsale, start, limit);
			result.setItemList(list);
		}
		return result;
	}
	/**
	 * 删除商品
	 * @param principal
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/goods/deleteGood/{goodId}",method=RequestMethod.DELETE)
	@PreAuthorize(value=GhckAplication.shop)
	public Result deleteGood(Principal principal,@PathVariable("goodId")Integer goodId){
		Result result = new Result();
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		Seller seller = sellerService.findSellerByUsrId(user.getUserId());
		if(seller != null){
			goodsService.deleteGood(seller.getId(), goodId);
		}
		return result;
	}
	/**
	 * 提交审核
	 * @param principal
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/goods/reviewe/{goodId}",method=RequestMethod.PUT)
	@PreAuthorize(value=GhckAplication.shop)
	public Result reviewe(Principal principal,@PathVariable("goodId")Integer goodId){
		Result result = new Result();
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		Seller seller = sellerService.findSellerByUsrId(user.getUserId());
		if(seller != null){
			goodsService.revieweGood(seller.getId(), goodId);
		}
		return result;
	}
	
	/**
	 * 取消提交审核
	 * @param principal
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/goods/cancelReviewe/{goodId}",method=RequestMethod.PUT)
	@PreAuthorize(value=GhckAplication.shop)
	public Result cancelReviewe(Principal principal,@PathVariable("goodId")Integer goodId){
		Result result = new Result();
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		Seller seller = sellerService.findSellerByUsrId(user.getUserId());
		if(seller != null){
			goodsService.cancelRevieweGood(seller.getId(), goodId);
		}
		return result;
	}
	/**
	 * 上架
	 * @param principal
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/goods/shelves/{goodId}",method=RequestMethod.PUT)
	@PreAuthorize(value=GhckAplication.shop)
	public Result shelves(Principal principal,@PathVariable("goodId")Integer goodId){
		Result result = new Result();
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		Seller seller = sellerService.findSellerByUsrId(user.getUserId());
		if(seller != null){
			goodsService.shelvesGood(seller.getId(), goodId);
		}
		return result;
	}
	/**
	 * 下架
	 * @param principal
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/goods/xiajia/{goodId}",method=RequestMethod.PUT)
	@PreAuthorize(value=GhckAplication.shop)
	public Result xiajia(Principal principal,@PathVariable("goodId")Integer goodId){
		Result result = new Result();
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		Seller seller = sellerService.findSellerByUsrId(user.getUserId());
		if(seller != null){
			goodsService.xiajiaGood(seller.getId(), goodId);
		}
		return result;
	}
	/**
	 * 添加收藏
	 * @param principal
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/collect/addGoodCollect/{goodId}",method=RequestMethod.GET)
	@PreAuthorize(value=GhckAplication.shop_maker_user)
	public Result addGoodCollect(Principal principal,@PathVariable("goodId")Integer goodId){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		Result result = new Result();
		GoodCollect goodCollect = new GoodCollect();
		Date date = new Date();
		goodCollect.setGoodId(goodId);
		goodCollect.setUserId(user.getUserId());
		goodCollect.setCreateTime(date);
		goodCollect.setUpdateTime(date);
		goodsService.addGoodCollect(goodCollect);
		return result;
	}
	/**
	 * 删除收藏
	 * @param principal
	 * @param colectId
	 * @return
	 */
	@RequestMapping(value="/collect/deleteGoodCollect/{colectId}",method=RequestMethod.GET)
	@PreAuthorize(value=GhckAplication.shop_maker_user)
	public Result deleteGoodCollect(Principal principal,@PathVariable("colectId")Integer colectId){
		Result result = new Result();
		goodsService.deleteGoodCollect(colectId);
		return result;
	}
	/**
	 * 我的收藏列表
	 * @param principal
	 * @param start
	 * @param limit
	 * @return
	 */
	@RequestMapping(value="/collect/myGoodCollects",method=RequestMethod.GET)
	@PreAuthorize(value=GhckAplication.shop_maker_user)
	public ResultList<GoodCollectRes> myGoodCollects(Principal principal,
			@RequestParam(defaultValue = "0") Integer start,
            @RequestParam(defaultValue = "20") Integer limit){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		GoodsReq goodsReq = new GoodsReq();
		goodsReq.setStart(start);
		goodsReq.setLimit(limit);
		goodsReq.setUserId(user.getUserId());
		ResultList<GoodCollectRes> result = new ResultList<GoodCollectRes>();
		List<GoodCollectRes> list = goodsService.myGoodCollects(goodsReq);
		result.setItemList(list);
		return result;
	}
	
	
	/**
	 * 购物车列表
	 * @return
	 */
	@ApiOperation(value="购物车列表")
	@PreAuthorize(GhckAplication.shop_maker_user)
	@RequestMapping(value = "/shopping_cart/list")
	public ResultList<ShoppingCartRes> shoppingCartList(Principal principal,ShoppingCartReq shoppingCartReq){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		shoppingCartReq.setUserId(user.getUserId());
		ResultList<ShoppingCartRes> result = new ResultList<ShoppingCartRes>();
		result.setItemList(shoppingCartService.getShoppingCartList(shoppingCartReq));
		return result;
	}
	
	/**
	 * 购物车商品总数
	 * @return
	 */
	@ApiOperation(value="购物车商品总数")
	@PreAuthorize(GhckAplication.shop_maker_user)
	@RequestMapping(value = "/shopping_cart/count")
	public ResultObject<Integer> shoppingCartCount(Principal principal,ShoppingCartReq shoppingCartReq){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		shoppingCartReq.setUserId(user.getUserId());
		ResultObject<Integer> result = new ResultObject<Integer>();
		result.setDomain(shoppingCartService.getShoppingCartNum(shoppingCartReq));
		return result;
	}
	
	/**
	 * 新增购物车
	 * @param principal
	 * @param shoppingCartReq
	 * @return
	 */
    @ApiOperation(value="新增购物车")
    @PreAuthorize(GhckAplication.shop_maker_user)
	@RequestMapping(value = "/shopping_cart/add" ,method=RequestMethod.POST)
	public ResultObject<ShoppingCartReq> addShoppingCart(Principal principal,@RequestBody ShoppingCartReq shoppingCartReq){
    	AjkUserDetails user = AjkUtil.getUserDetails(principal);
		shoppingCartReq.setUserId(user.getUserId());
		ShoppingCartReq scr = shoppingCartService.addShoppingCart(shoppingCartReq);
		return new ResultObject<ShoppingCartReq>(scr);
	}
	
	/**
	 * 新增购物车
	 * @param principal
	 * @param shoppingCartReq
	 * @return
	 */
    @ApiOperation(value="更新购物车商品数量")
    @PreAuthorize(GhckAplication.shop_maker_user)
	@RequestMapping(value = "/shopping_cart/update" ,method=RequestMethod.PUT)
	public Result updateShoppingCart(Principal principal,@RequestBody ShoppingCartReq[] shoppingCartReq){
    	AjkUserDetails user = AjkUtil.getUserDetails(principal);
    	shoppingCartService.updateShoppingCart(user.getUserId(), shoppingCartReq);
		return new Result();
	}
	
	/**
	 * 删除购物车
	 * @param principal
	 * @param id
	 * @return
	 */
    @ApiOperation(value="删除购物车")
    @PreAuthorize(GhckAplication.shop_maker_user)
	@RequestMapping(value = "/shopping_cart/{id}" ,method=RequestMethod.DELETE)
	public Result deleteShoppingCart(Principal principal,@PathVariable("id") Integer id ){
    	AjkUserDetails user = AjkUtil.getUserDetails(principal);
		ShoppingCartReq scr = new ShoppingCartReq();
		scr.setId(id);
		scr.setUserId(user.getUserId());
		shoppingCartService.deleteShoppingCart(scr);
		return new Result();
	}
	

}